package com.nubia.controller;


import com.nubia.entity.User;
import com.nubia.service.UserService;
import com.nubia.utils.JwtUtils;
import com.nubia.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/login")
    public Map<String,Object> login(@RequestBody User user){
        log.info("当前登录用户信息：[{}]",user.toString());
        try {
            User userLG = userService.login(user);
            userLG.setPassword("********");
            if(userLG != null){
                String token = JwtUtils.creatToken(userLG.getUser_id());
                Map<String,Object> map = new HashMap<>();
                map.put("deatail","登录成功");
                map.put("status",true);
                map.put("token",token);
                map.put("data",userLG);
                return map;
            }
            return Result.resultDataString("登录失败", false, "请注册后重试！");


        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.resultDataString("", false, "error");
    }


    @RequestMapping("/register")
    public Map<String,Object> register(@RequestBody User user){
        //调用userService中的注册方法
        //设置一个username 随机
        user.setUser_id(UUID.randomUUID().toString());

        if(user.getUser_name() == null || user.getPassword() == null)
        {
            return  Result.resultDataString("账号或者密码不能为空",false,"error");
        }else {
            try {
                userService.register(user);
                return  Result.resultDataString("注册成功",true,"success");
            } catch (Exception e) {
                e.printStackTrace();
                return  Result.resultDataString("用户名重复",false,"请重新输入");
            }
        }
        //return  Result.resultDataString("系统异常",false,"请联系管理员");
    }

}
